<?php

declare (strict_types=1);

namespace app\dao\v1\recovery;

use app\dao\BaseDao;
use app\model\v1\recovery\RecoveryProduct;

class RecoveryProductDao extends BaseDao
{

    /**
     * 设置模型
     * @return string
     */
    protected function setModel(): string
    {
        return RecoveryProduct::class;
    }


    public function search(array $where = []){
        return parent::search($where)->when(isset($where['word']) && $where['word'], function ($query) use ($where) {
            $query->where('product_name', 'LIKE', '%' . trim($where['word']) . '%');
        })->when(isset($where['type']) && $where['type'], function ($query) use ($where) {
            $query->where('type', $where['type']);
        })->when(isset($where['status']) && $where['status'], function ($query) use ($where) {
            $query->where('status', '=', $where['status']);
        });
    }


    /**
     * 首页 - top区域 - 搜索商品列表
     * @param array $where
     * @param string $field
     * @param int $page
     * @param int $limit
     * @param string $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $where, string $field = '*', int $page = 0, int $limit = 0, string $order = 'id desc')
    {
        return $this->search($where)->field($field)
            ->with([
                'category' => function ($query) {
                    $query->field(['id', 'pid', 'cate_name']);
                },
                'user' => function ($query) {
                    $query->field(['uid', 'nickname', 'avatar']);
                },
            ])
            ->when($page != 0 && $limit != 0, function ($query) use ($page, $limit) {
                $query->page($page, $limit);
            })->when($order, function ($query) use ($order) {
                if ($order == 'rand') {
                    $query->orderRand();
                } else if ($order) {
                    $query->order($order);
                } else {
                    $query->order('sort desc,id desc');
                }
            })->select()->toArray();
    }


    public function getListCount(array $where, string $field = '*')
    {
        return $this->search($where)->field($field)
            ->with(['category' => function ($query) {
                $query->field(['id', 'pid', 'cate_name']);
            }])
            ->count();
    }

}